<?php

namespace App\Listeners\Subscriber;

use Exception;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Events\Project\DeletedEvent;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\Project\DetachedStaffEvent;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProjectEventSubscriber
{
	/**
	 * 删除项目成功后触发业务逻辑
	 *
	 * Date: 16/05/2018
	 * @author George
	 * @param DeletedEvent $event
	 */
	public function onDeleted(DeletedEvent $event)
	{
		try {
			DB::table('users')
				->where('project_id', $event->project->id)
				->update(['project_id' => 0]);
		} catch (Exception $exception) {
			Log::error($exception->getMessage());
		}
	}

	/**
	 * 当从项目中移除人员时触发逻辑
	 *
	 * Date: 16/05/2018
	 * @author George
	 * @param DetachedStaffEvent $event
	 */
	public function onDetachedStaff(DetachedStaffEvent $event)
	{
		try {
			/**
			 * 当人员被移除项目时，删除之后的排班记录
			 */
			DB::table('schedules')
				->where('project_id', $event->project_id)
				->where('user_id', $event->user_id)
				->whereDate('date', '>', $event->date)
				->delete();
		} catch (Exception $exception) {
			Log::error($exception->getMessage());
		}
	}

	/**
	 * 定义订阅事件
	 *
	 * Date: 16/05/2018
	 * @author George
	 * @param Dispatcher $events
	 */
	public function subscribe(Dispatcher $events)
	{
		$events->listen(
			'App\Events\Project\DeletedEvent',
			'App\Listeners\Subscriber\ProjectEventSubscriber@onDeleted'
		);

		$events->listen(
			'App\Events\Project\DatchedStaffEvent',
			'App\Listeners\Subscriber\ProjectEventSubscriber@onDetachedStaff'
		);
    }
}
